package com.xkw.autocode.web.codeexport.ao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xkw.autocode.jdbc.entity.TableEntity;
import com.xkw.autocode.jdbc.mysql.JdbcExecutor;
import com.xkw.autocode.service.DatabaseConfigService;
import com.xkw.autocode.vo.DatabaseConfigVo;
import com.xkw.autocode.web.codeexport.ao.CodeExportAo;

/**
 * “数据库配置表” Ao实现类
 * 
 * @author auto
 */
@Service("codeExportAo")
public class CodeExportAoImpl implements CodeExportAo {

	@Autowired
	private DatabaseConfigService databaseConfigService;

	@Override
	public List<TableEntity> queryTables(Long databaseId) {
		return queryTables(databaseId, false, null);
	}

	@Override
	public List<TableEntity> queryTables(Long databaseId, boolean queryColumn, String tableNames) {
		if (databaseId == null) {
			return Collections.emptyList();
		}
		DatabaseConfigVo databaseConfigVo = databaseConfigService.findById(databaseId);

		JdbcExecutor jdbcExecutor = new JdbcExecutor(databaseConfigVo.getDbUrl(), databaseConfigVo.getDbUsername(),
				databaseConfigVo.getDbPassword());

		List<TableEntity> tableList = jdbcExecutor.getTables();

		// 过滤表
		if (StringUtils.isNotEmpty(tableNames) && !tableList.isEmpty()) {
			List<TableEntity> newTableList = new ArrayList<>();
			Set<String> tableNameSet = this.getTableNameSet(tableNames);

			for (TableEntity tableEntity : tableList) {
				if (tableNameSet.contains(tableEntity.getTableName())) {
					newTableList.add(tableEntity);
				}
			}
			tableList = newTableList;
		}

		if (queryColumn && !tableList.isEmpty()) {

			for (TableEntity tableEntity : tableList) {
				tableEntity.setColumns(jdbcExecutor.getTableColumnInfo(tableEntity.getTableName()));
			}
		}

		jdbcExecutor.close();

		return tableList;
	}

	private Set<String> getTableNameSet(String tableNames) {
		if (StringUtils.isEmpty(tableNames)) {
			return Collections.emptySet();
		}
		return new HashSet<>(Arrays.asList(tableNames.split(",")));
	}
}
